﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UFC.Common;
using System.Data;
using System.Xml;
using System.Data.OracleClient;
using UFC.DBUtility;
using System.Configuration;

namespace MESWorkCenterDispatching
{
   public  class SendDispatchingData
    {
       public void RunDispatchingSync()
       {
           SendDNC();
       }
       /// <summary>
       /// 派工单获取
       /// </summary>
       /// <returns></returns>
       private DataTable GetDispatching(string redordtype)
       {
           try
           {
               StringBuilder strSql = new StringBuilder();
               strSql.AppendLine("select wfs.workflowstepname,nc.ncarrangementsid,c.containername,m.mfgordername,pb.productname,sb2.specname,s.specno,s.parentspecno,t.teamname,");
               strSql.AppendLine(" e.fullname,nc.createdate,r.resourcename,wfb.workflowname,nc.needdate from ncarrangements nc ");
               strSql.AppendLine(" left join container c on c.containerid=nc.containerid");
               strSql.AppendLine(" left join product p on p.productid = c.productid  ");
               strSql.AppendLine(" left join productbase pb on pb.productbaseid = p.productbaseid ");
               strSql.AppendLine(" left join workflowstep wfs on wfs.workflowstepid=nc.workflowstepid");
               strSql.AppendLine(" left join mfgorder m on m.mfgorderid=c.mfgorderid");
               strSql.AppendLine(" left join specbase sb on sb.specbaseid=wfs.specbaseid");
               strSql.AppendLine(" left join spec s on s.specid = nvl(sb.revofrcdid,wfs.specid)");
               strSql.AppendLine(" left join specbase sb2 on sb2.specbaseid=s.specbaseid");
               strSql.AppendLine(" left join team t on t.teamid=nc.teamid");
               strSql.AppendLine(" left join employee e on e.employeeid=nc.employeeid");
               strSql.AppendLine(" left join resourcedef r on r.resourceid = nc.resourceid");
               strSql.AppendLine(" left join workflow wf on wf.workflowid = wfs.workflowid");
               strSql.AppendLine(" left join workflowbase wfb on wfb.workflowbaseid = wf.workflowbaseid");
               strSql.AppendFormat(" left join WriteToERPRecord werpr on werpr.recordid=nc.ncarrangementsid and werpr.recordtype='{0}'", redordtype);
               strSql.AppendFormat(" where nc.isintegration=0 and werpr.recordid is  null and nc.createdate>=sysdate-100", ConfigurationManager.AppSettings["DispatchingDate"]);
               string strTmp = strSql.ToString();

               //
               DataSet myDS = OracleHelper.Query(strSql.ToString());
               if (myDS == null)
               {
                   return null;
               }
               if (myDS.Tables.Count == 0)
               {
                   return null;
               }
               return myDS.Tables[0];
           }
           catch (Exception e)
           {
               LogHelp.WriteError("派工单获取", e);
               return null;
           }
       }

       private void SendDNC()
       {
           DataTable mydt = GetDispatching(m_DisDNCRecordType);
           if (mydt == null)
           {
               LogHelp.WriteLog("没有可处理的派工单DNC");
           }
           Dictionary<string, string> strList;

           MESAndDNC.DncService dnc = new MESAndDNC.DncService();

           foreach (DataRow dr in mydt.Rows)
           {
               strList = new Dictionary<string, string>();
               strList.Add("partno", dr["productname"].ToString());//零件号
               strList.Add("artno", dr["workflowname"].ToString());//工艺路线名称
               string specname = dr["specname"].ToString();
               string strSpecNameTmp = specname.Replace(dr["productname"].ToString() + "-", "");
               string strSpecNo = dr["specno"].ToString();
               if (string.IsNullOrWhiteSpace(strSpecNo))
               {
                   string[] strArray = specname.Split('-');
                   if (strArray.Length >= 3)
                   {
                       strSpecNo = strArray[strArray.Length - 2];
                   }
               }
               strList.Add("operno", strSpecNo);//工序号
               strList.Add("operuser", dr["fullname"].ToString());//人员编号               
               strList.Add("machine", dr["resourcename"].ToString());//机床编号
               strList.Add("operdate", dr["createdate"].ToString());//生产准备日期 update:Wangjh 派工日期->生产准备日期
               strList.Add("note", dr["workflowstepname"].ToString());//备注 工序名update:Wangjh  派工单号->工序名
               strList.Add("pgd", dr["ncarrangementsid"].ToString());//唯一ID update:Wangjh 派工单号->唯一ID
               string strXML = CreateXMLForDispatchingDNC(strList);
               LogHelp.WriteLog("推送的XML："+strXML);
               string resXML = dnc.DNC_Get_Task_Service(strXML);
               LogHelp.WriteLog("接收的XML：" + resXML);

               if (GetRcvXML(resXML))
               {
                   OracleDAL.InsertSyncRecord(dr["ncarrangementsid"].ToString(), m_DisDNCRecordType, "成功", 0);
                   string updateSql = string.Format(" update ncarrangements set isintegration=1 where ncarrangementsid='{0}'", dr["ncarrangementsid"]);
                   OracleHelper.ExecuteSql(updateSql);
               }
               else
               {
                   string updateSql = string.Format(" update ncarrangements set isintegration=1 where ncarrangementsid='{0}'", dr["ncarrangementsid"]);
                   OracleDAL.InsertSyncRecord(dr["ncarrangementsid"].ToString(), m_DisDNCRecordType, resXML, 1);
               }

           }
       }
      
       /// <summary>
       /// 生产派工单XML
       /// </summary>
       /// <param name="strList"></param>
       /// <returns></returns>
       private string CreateXMLForDispatchingDNC(Dictionary<string, string> strList)
       {
           try
           {
               XmlDocument doc = new XmlDocument();
               doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", ""));
               XmlNode ReqNode = doc.CreateElement("ReqMsg");
               XmlNode headerNode = doc.CreateElement("header");
               XmlNode senderNode = doc.CreateElement("sendSysName");
               senderNode.InnerText = "APP_MES";
               XmlNode rcvNode = doc.CreateElement("rcvSysName");
               senderNode.InnerText = "APP_DNC";

               headerNode.AppendChild(senderNode);
               headerNode.AppendChild(rcvNode);
               ReqNode.AppendChild(headerNode);
               XmlNode documentNode = doc.CreateElement("document");
               string strData = "";
               foreach (KeyValuePair<string, string> _key in strList)
               {
                   strData = string.Format("{0}<{1}>{2}</{1}>", strData, _key.Key, _key.Value);
               }
               documentNode.AppendChild(doc.CreateCDataSection(strData));
               ReqNode.AppendChild(documentNode);
               doc.AppendChild(ReqNode);
               return doc.InnerXml;

            


           }
           catch (Exception e)
           {
               LogHelp.WriteError("生产派工单XML", e);
               return string.Empty;
           }
       }
     
       /// <summary>
       /// 获取ERP反馈XML
       /// </summary>
       /// <param name="strXML"></param>
       /// <returns></returns>
       private bool GetRcvXML(string strXML)
       {
           XmlDocument doc = new XmlDocument();
           doc.LoadXml(strXML);
           string isSuccess = doc.SelectSingleNode("RespMsg/header/isSuccess").InnerText;
           string meaasge = doc.SelectSingleNode("RespMsg/header/message").InnerText;

           if (isSuccess=="true" || meaasge =="S"  )
              { 
			   LogHelp.WriteLog(strXML);//TEST 反馈的XML
			  return true;
			  }
           else
           {
               LogHelp.WriteLog(meaasge);
			    LogHelp.WriteLog(strXML);//TEST 反馈的XML
               return false;
           }
       }
       private const string m_DisERPRecordType = "ERPdispatching";
       private const string m_DisDNCRecordType = "DNCdispatching";
    }
}
